package com.harboursoftware.xstorage.operations;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.ListMultimap;
import com.harboursoftware.xstorage.XStorageException;
import com.harboursoftware.xstorage.ac.AccessControlPolicy;
import com.harboursoftware.xstorage.ac.Permission;
import com.harboursoftware.xstorage.fs.BucketNotExistException;
import com.harboursoftware.xstorage.model.XBucket;
import com.harboursoftware.xstorage.model.XElement;
import com.harboursoftware.xstorage.model.XUser;
import com.harboursoftware.xstorage.results.ErrorResult;
import com.harboursoftware.xstorage.results.GetBucketResult;
import com.harboursoftware.xstorage.results.Result;

/**
 * GET Bucket (List Objects)
 * @author Simon Leung
 * @since 0.1
 */
public class GetBucket extends Operation {
	private final static Logger log = LoggerFactory.getLogger(GetBucket.class);
    @Override
    public Result execute(XUser requester, XElement element, ListMultimap<String, String> headers, Map<String, String> parameters) {
    	log.debug("execute");
    	XBucket bucket = (XBucket)element;
        try {
            fileSystem.loadBucketACP(bucket);
            AccessControlPolicy acp = bucket.getAcp();
            if(!acp.checkPermission(requester, getRequiredPermission())) {
                return ErrorResult.create(ErrorResult.Type.ACCESS_DENIED);
            }
            //parameters
            String delimiter = parameters.get("delimiter");
            String marker = parameters.get("marker");
            String prefix = parameters.get("prefix");
            
            String maxKeysString = parameters.get("max-keys");
            
            int maxKeys = 1000;
            if(maxKeysString != null) {
                try {
                    maxKeys = Integer.valueOf(parameters.get("max-keys"));
                } catch (NumberFormatException e) {
                    // TODO 异常处理
                }
            }
            fileSystem.listObjects(bucket, delimiter, marker, maxKeys, prefix);
            
            GetBucketResult result = new GetBucketResult(bucket);
            return result;
            
        } catch (BucketNotExistException e) {
        	ErrorResult errorResult = ErrorResult.create(ErrorResult.Type.NO_SUCH_BUCKET);
        	errorResult.addOtherInfo("BucketName", bucket.getName());
        	return errorResult;
        } catch (XStorageException e) {
          //TODO:考虑： 这里应该是连接IOException 还是 Exception？,log下错误代码
            log.error("error occured when get bucket", e);
            return ErrorResult.create(ErrorResult.Type.INTERNAL_ERROR);
        }
    }
    

    @Override
    public Permission getRequiredPermission() {
        return Permission.READ;
    }
}
